package startup;

import org.mybatis.generator.extend.all_table_generator.HumpAndUnderlineConverter;
import org.mybatis.generator.extend.generate_table_by_model.JdbcTypeJavaTypeMappingUtil;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * 根据domain包下的实体类生成数据库表结构SQL语句<br/>
 * 实现比较简单, 只能处理JavaType是Integer, Long, BigDecimal, Date, String类型的字段<br/>
 * JavaType对应的JdbcType可以参考{@link org.mybatis.generator.extend.generate_table_by_model.JdbcTypeJavaTypeMappingUtil}<br/>
 * id 字段默认主键,自增, 其他字段默认可为空
 * @author lixiangke
 * @date 2017/11/30
 */
public class DatabaseSqlGenerator {
    public static void main(String[] args) throws ClassNotFoundException, IOException {
        String domainPackage = "domain";
        String tablePrefix = "t";
        ClassPathResource resource = new ClassPathResource(domainPackage);
        File[] files = resource.getFile().listFiles();
        for (File f : files) {
            // 得到的domainName默认是xDomain.class, 故截取
            String domainName = f.getName().substring(0, f.getName().length() - 6);
            String tableName = tablePrefix + HumpAndUnderlineConverter.humpToLine2(domainName);
            Class clazz = Class.forName(domainPackage + "." + domainName);
            StringBuffer sb = new StringBuffer();
            sb.append("CREATE TABLE " + tableName + "(");
            for (Field field : clazz.getDeclaredFields()) {
                String fieldName = field.getName();
                String javaType = field.getType().getName();
                String jdbcType = JdbcTypeJavaTypeMappingUtil.getJdbcType(javaType);
                String jdbcTypeLength = JdbcTypeJavaTypeMappingUtil.getJdbcTypeLength(jdbcType);
                fieldName = HumpAndUnderlineConverter.humpToLine2(fieldName);
                sb.append(fieldName + " " + jdbcType + "(" + jdbcTypeLength + ")" + isPrimaryKey(fieldName) + ",");
            }
            sb.append("PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ROW_FORMAT=COMPACT;");
            System.out.println(sb);
        }

    }

    private static String isPrimaryKey(String fieldName) {
        if ("id".equals(fieldName)) {
            return " NOT NULL AUTO_INCREMENT";
        } else {
            return "";
        }
    }
}
